/**
 * 窗口打开工具类.
 */
define(['jquery'], function ($) {
	/**
	 * 最后请求时间,用于检测会话
	 */
	var lastRequestTime = new Date();
	/**
	 * 判断是否chrome浏览器.
	 */
	function isChrome() {
		var res = false;
		if (window.navigator.userAgent.indexOf("Chrome") !== -1) {
			res = true;
		}
		return res;
	}
	
	/**
	 * 最大化打开窗口.
	 * @param url 地址
	 * @param title 标题
	 */
	function openWindow(url,title) {
		require(['ecp.utils.des',"ecp.utils"],function( $des,$utils){
			var openUrl = url;
			var width = screen.width ;
			var height = screen.height ;
			if (height == 768 ) height -= 80 ;
			if (height == 600 ) height -= 60 ;
			var szFeatures = "top=0," ; 
			szFeatures +="left=0," ;
			szFeatures +="width="+width+"," ;
			szFeatures +="height="+height+"," ;
			szFeatures +="channelmode =yes," ;
			szFeatures +="directories=no," ;
			szFeatures +="status=yes," ;
			szFeatures +="menubar=no," ;
			szFeatures +="scrollbars=yes," ;
			szFeatures +="resizable=yes" ;
			if (openUrl.indexOf("/grm") > -1) {
				if (openUrl.indexOf("?") == -1) {
					openUrl += "?";
				}
				openUrl = $utils.addArguments(openUrl, "closeModel", 1, true);
				openUrl = $des.encodeSearch(openUrl);
				if (title) {
					if (openUrl.indexOf("?") == -1) {
						openUrl += "?";
					}
					var t = encodeURI(title);
					openUrl = $utils.addArguments(openUrl, "_winTitle", t);
				}
			}
			var win;
			if (isNaN($utils.getIEVersion())) {
				if (window.externalHost) {
					//chromeframe打开窗口用中间页面打开，绕开chrome加载规则
					openUrl = "/grm/ecp3/bsportal/openBridge.shtml?loadUrl=" + $des.encodeBase64(openUrl);
					$utils.openWindowInIE(openUrl);
				} else {
					// 检测是否node-webkit运行
					var gui = null;
					var isWebkit = false;
					if (typeof require !== 'undefined') {
						try {
							gui = require('nw.gui');
						} catch (e) {
							window.console && window.console.info("no require[nw.gui] defined");
						}
						//补偿判断
						if (typeof nwDispatcher !== 'undefined' && $.isFunction(nwDispatcher.requireNwGui)) {
							isWebkit = true;
							try {
								gui = nwDispatcher.requireNwGui();
							} catch(e) {
								window.console && window.console.info("call nwDispatcher.requireNwGui fail.");
							}
						}
					} else if (typeof nwDispatcher !== 'undefined' && $.isFunction(nwDispatcher.requireNwGui)) {
						gui = nwDispatcher.requireNwGui();
					}
					if (gui) {
						try {
							var win = gui.Window.get(window.open(openUrl));
							if (win) {
								win.maximize();
							}
						} catch (e) {
							window.console && window.console.info("打开窗口出现异常:" + e.message);
						}
					} else {
						if (isChrome()) {
							//跨域地址在chrome下不会多页签打开
							var crossSite = false;
							if (openUrl.indexOf("http") ===0 && openUrl.indexOf(location.origin) == -1) {
								crossSite = true;
							}
							if (crossSite || isWebkit) {
								win = window.open(openUrl,"",szFeatures);
							} else {
								win = window.open(openUrl);
							}
						} else {
							win = window.open(openUrl);
						}
						if (win && win.opener) {
							win.opener = null;
						}
					}
				}
			} else {
				win = window.open(openUrl,"",szFeatures);
				if (win && win.opener) {
					win.opener = null;
				}
			}
		})
	}
	/**
	 *注册页面关闭事件
	 */
    function registAutoClose(timeout) {
    	if(!timeout){
    		timeout = 1500;
    	}
    	window.currentTokenId = $.cookie("ecpDataContext.tokenId");
    	var isRelogin = false;
    	window.tokenMonitor = setInterval(function() {
    		var token = $.cookie("ecpDataContext.tokenId");
    		if (token == null && !isRelogin) {
    			window.unloadFlag = true;
    			window.opener = null;
				window.open('', '_self');
				window.close();
    		}
    		if ((token != null || currentTokenId != null) && token != currentTokenId) {
    			window.unloadFlag = true;
    			window.location.reload();
    		}
    	}, timeout);
    }
	/**
	 * 绑定关闭window窗口前事件，给予提示是否需要关闭
	 * @param {Function} fun 回调
	 */
	function bindBeforeunload(fun){
		//处理webkit客户端问题
		try{
			var req = window.require, gui;
			if(req && !req("nw.gui")){
				gui = req("nw.gui");
			}else{
				if (typeof nwDispatcher !== 'undefined' && $.isFunction(nwDispatcher.requireNwGui)) {
					gui = nwDispatcher.requireNwGui();
				}
			}
			if (gui) {
				var win = gui.Window.get();
				if (win) {
					win.on("close",function(){
						//var bunloadFun = window.onbeforeunloadFun;
						if($.isFunction(fun) && !window.notBeforeWinFun){
							var res = fun();
							if(res){
								require(["ecp.component.dialog","ecp.utils.i18n"], function(dialog,i18n){
									dialog.show({
										title: i18n.F0000.sExpTitle,
										content: res,
										isTip: true,
										showCloseButton : false,
										otherButtons: [i18n.select.cancel,i18n.select.sure],
										otherButtonStyles: ["btn-default", "btn-primary"],
										clickButton: function(sender, modal, index){
											if(index === "0"){
												modal.modal('hide');
											} else if (index === "1"){
												 //添加关闭后事件
												if(typeof window.onAfterClose === "function") {
													window.onAfterClose();
												}
											}
										}
									});
								});
							}
						}
						this.close(true);
					});
					return;
				}
			}
		}catch(e){
			//无需处理
		}
		//绑定关闭window窗口前事件，给予提示是否需要关闭
		window.onbeforeunload = function(){
			//onbeforeunloadFun回调函数，如果返回空或者false都不给提示
			//var bunloadFun = fun;//window.onbeforeunloadFun;
			if($.isFunction(fun) && !window.notBeforeWinFun){
				var res = fun();
				if(res){
					return res;
				}
			}else{
				window.notBeforeWinFun = false;
			}
		}
	}
	//倒计时时间
	var timeInterval = 30 * 60 * 1000;//2000;
	/**
	 * 注册重新登陆
	 *  @param {Number} timeout 秒 延迟关闭
	 */
	function registReLogin(){
    	window.loginStatMonitor = setInterval(function(){
    		checkSessionValide();
    	}, timeInterval);
	}

	/**
     * 校验会话是否还生效，间隔半小时.
     */
    function checkSessionValide() {
		require(["ecp.service"],function(ecp){
			var now = new Date();
			var nowSec = now.getTime();
			var last = lastRequestTime.getTime();
			var flag = true;
			if (nowSec - last > timeInterval) {
				var token = $.cookie("ecpDataContext.tokenId");
				var context = ecp.RemoteService.doPost(
					"com.ygsoft.ecp.core.framework.context.IEcpDataContextService","findDataContext",[token]);
				lastRequestTime = now;
				if (context == null || context.loginContext == null) {
					flag = false;
				}
				var lc = context.loginContext;
				var userId = lc.userId;
				var orgId = lc.loginOrgId;
				if (userId == null || orgId == null) {
					flag = false;
				}
			}
			if(flag && !$("#reloginModalDlg").is(":visible")){
				showReloginDlg();
			}
		});
    }

	/**
	 * 返回令牌.
	 */
	var RET_TOKENID = "RET_TOKENID";
	/**
	 * 获取客户端IP.
	 */
	function getIpAddress(){
		var resdata = $.ajax({
			url: "/grm/ecp/IpGetterServlet?",
			type: 'POST',
			async:false
		});
		return resdata.responseText;
	}
	/**
	 * 加密公钥.
	 */
	var pk = {
	    n:"55ad4b6c739452c01710d7763455abca358fc472a243517e743ef1d69618b6396fe7a76409cef96b716cb73723235f56614e19ee16bd0e0a8f47b8639ef15b6a95124e984757133060114472ef20ff18087cef05647d02ed70c3e7a9afb1ed0023cedcf64f9eea0d8ae0be7d68938f5c413077978d5435621f2c52524dbf8a97",
	    e: "10101"
	}
	/**
     * 显示重登陆对话框.
     * @param callback 回调函数
     */
    function showReloginDlg(callback) {
		require(["ecp.service","ecp.utils.des","encrypt.jsbn","encrypt.rsa","encrypt.rng","encrypt.prng"],function(ecp,des){
			var dc = ecp.DataContextUtil.getEcpDataContext();
			var args = [];
			var is4A = $.cookie("4A"); 
			if (arguments.length > 1) {
				for (var i=1; i < arguments.length;i++) {
					args.push(arguments[i]);
				}
			}
			/**
			 * RSA非对称加密.
			 */
			function secEncrypt(value) {
				var rsa = new RSAKey();
				rsa.setPublic(pk.n, pk.e);
				return rsa.encrypt(value);
			}
			/**
			 * 显示模态窗口.
			 */
			function showModal() {
				var dlg = $("#reloginModalDlg");
				var userName = dc.loginContext.userName;
				var userJQ = $("#reloginUser",dlg);
				userJQ.val(userName);
				
				var unitName=   dc.loginContext.loginOrgName;
				var unitJQ = $("#reloginUnitName", dlg)
				unitJQ.val(unitName);
				dlg.modal();
				$("#reloginPwd", dlg).focus();
				
				var dialog = $("#reloginModalDlg .modal-dialog");
				var height = 368;//重登录对话框的高度
				var bodyHeight = document.documentElement.clientHeight;
				var top = (bodyHeight - height)/2;
				dialog.css("top", top + "px");
				dlg.on('shown.bs.modal', function () {
					$("#reloginPwd").focus();
				});
				if(is4A) {
					$("#reloginUser").parents(".form-group").hide();
					$("#reloginPwd").parents(".form-group").hide();
					$("#reloginUnitName").parents(".form-group").hide();
				}
			}
			var cont = $("#reloginDlgContainer");
			var context = {cb : callback, args : args};
			if (cont.length === 0) {
				$.ajax({
					url : "/grm/ecp/webcore/business/relogin.html",
					type : 'GET',
					async : true,
					success : function(resdata, textStatus, jqXHR) {
						if ($("#reloginModalDlg").length > 0) {
							return;
						}
						var html = resdata;
						var $body = $("body");
						$body.append(html);
						showModal();
						var dlg = $("#reloginModalDlg");
						var btn = $("#doRelogin", dlg);
						var pwdJQ = $("#reloginPwd", dlg);
						btn.unbind("click");
						btn.click(function() {
								if(is4A) {
									window.unloadFlag = true;
									dlg.modal("hide");
									window.opener = null;
									window.open('', '_self');
									window.close();
								}
								window.unloadFlag = true;
								var pwd = pwdJQ.val();
								var userName = dc.loginContext.userName;
								var orgId = dc.loginContext.loginOrgId;
								var orgName = dc.loginContext.loginOrgName;
								var desUserNm = des.ENCRYSTRING_HEAD + des.doEncrypt(userName, des.ENCRY_FIRST_KEY,des.ENCRY_SECOND_KEY,des.ENCRY_THIRD_KEY);
								var data = [getIpAddress(), desUserNm, secEncrypt(pwd), orgId, orgName];
								ecp.RemoteService.doPost("com.ygsoft.ecp.service.security.service.context.ILoginService", "quickLogin", data, function(resdata) {
//									if(resdata.is)
									var data = {};
//									if (resdata && resdata["RET_STATUS"]) {
//										if(resdata[RET_TOKENID]) {
//											window.currentToken = resdata[RET_TOKENID];
//											document.cookie = CONST.TOKEN + "=" + resdata[RET_TOKENID] + "; path=/";
//										}
//										callback(resdata);
//									} else {
//										data.RET_STATUS = false;
//										data.RET_DESC = "登录失败。";
//										if (resdata) {
//											data.RET_DESC = resdata["RET_DESC"];
//										}
//										callback(data);
//									}
								});
						})
						function callback(res){
							var alt = $("#reloginAlert", dlg);
							if (res["RET_STATUS"]) {
								alt.hide();
								dlg.modal("hide");
								this.cb && this.cb.apply(null,this.args);
							} else {
								var hint = $("#reloginHint", dlg);
								hint.html(res["RET_DESC"]);
								alt.show();
							}
							window.location.reload();
						}
						pwdJQ.keypress(function(e){
							if (e.which == 13) return;
							$("#reloginAlert", dlg).hide();
						});
						dlg.keypress(function(e) {
							if (e.which == 13) {
								btn.click();
							}
						});
					}
				})
			} else {
				$("#reloginPwd").val("");
				showModal();
			}
		});
    }
	
    //registReLogin();

	return {
		openWindow : function(url,title) {
			if (!url) return;
			openWindow(url, title);
		},
		/**
		 * 自动根据门户退出而关闭页面
		 * @param {Number} timeout 秒 延迟关闭
		 */
		registAutoClose : function(timeout){
			registAutoClose(timeout);
		},
		/**
		 * 绑定关闭window窗口前事件，给予提示是否需要关闭
		 * //var fun = function(){
		 * //	return "系统可能不会保护您所做的更改。";
		 * // }
		 *  @param {Function} fun 回调,函数返回提示信息
		 */
		registBeforeunload : function(fun){
			bindBeforeunload(fun);
		},
		/**
		 * 注册重新登陆
		 *  @param {Number} timeout 秒 延迟关闭
		 */
		registReLogin : function(timeout){
			registReLogin(timeout);
		}
	}
});